package com.yao.controller;

import com.yao.config.ProjectUrlConfig;
import com.yao.config.WechatAccountConfig;
import com.yao.enums.ResultEnum;
import com.yao.exception.WeixinSellException;
import com.yao.service.WxOpenService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.net.URLEncoder;

/**
 * User: 姚宏武
 * Date: 2017/11/21
 * Time: 15:08
 * Email：401369870@qq.com
 * Description: 微信控制器
 */
@Controller
@RequestMapping("/wechat")
@Slf4j
public class WechatController {

    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private WxOpenService wxOpenService;

    @Autowired
    private ProjectUrlConfig projectUrlConfig;

    @Autowired
    private WechatAccountConfig accountConfig;


    /**
     * 访问授权
     *
     * @param returnUrl
     * @return
     */
    @GetMapping(value = "/authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl) {
        // 1、配置
        // 2、调用方法
        String url = projectUrlConfig.getWechatMpAuthorize() + "/wechat/userInfo";

        String redirectUrl = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAUTH2_SCOPE_USER_INFO, URLEncoder.encode(returnUrl));

        return "redirect:" + redirectUrl;
    }

    /**
     * 授权后获取用户信息
     *
     * @param code
     * @param returnUrl
     * @return
     */
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code,
                           @RequestParam("state") String returnUrl) {

        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            log.error("【微信网页授权】{}", e);
            throw new WeixinSellException(ResultEnum.WECHAT_MP_ERROR.getCode(), e.getError().getErrorMsg());
        }
        String openId = wxMpOAuth2AccessToken.getOpenId();
        return "redirect:" + returnUrl + "?openid=" + openId;
    }


    /**
     * 扫码登录授权
     * @TODO：此方法暂时没用，由于使用了他人的开发平台登录验证
     * @param returnUrl
     * @return
     */
    @GetMapping("/qrAuthorize")
    public String qrAuthorize(@RequestParam("returnUrl") String returnUrl) {
       /* String url = projectUrlConfig.getWechatOpenAuthorize() + "/wechat/qrUserInfo";

        String redirectUrl = wxOpenService.buildQrConnectUrl(url, WxConsts.QRCONNECT_SCOPE_SNSAPI_LOGIN, URLEncoder.encode(returnUrl));

        return "redirect:" + redirectUrl;*/

        // https://open.weixin.qq.com/connect/qrconnect?
        // appid=wx6ad144e54af67d87&
        // redirect_uri=http%3A%2F%2Fsell.springboot.cn%2Fsell%2Fqr%2F{OPENID}
        // &response_type=code&scope=snsapi_login&state={你的网址}

        String url = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=" + accountConfig.getOpenAppId() +
                "&redirect_uri=http%3A%2F%2Fsell.springboot.cn%2Fsell%2Fqr%2FoTgZpwVQkAOVQoDOdSdfFNk3lp_E" +
                "&response_type=code&scope=snsapi_login" +
                "&state=" + URLEncoder.encode(returnUrl);


        return "redirect:" + url;
    }


    /**
     * 授权后获取用户信息
     *
     * @param code
     * @return
     */
    @GetMapping("/qrUserInfo")
    public String qrUserInfo(@RequestParam("code") String code) {

        WxMpOAuth2AccessToken wxMpOAuth2AccessToken;
        try {
            wxMpOAuth2AccessToken = wxOpenService.getOAuth2AccessToken(code);
        } catch (WxErrorException e) {
            log.error("【微信网页授权】{}", e);
            throw new WeixinSellException(ResultEnum.WECHAT_OPEN_ERROR.getCode(), e.getMessage());
        }

        String openId = wxMpOAuth2AccessToken.getOpenId();
        return "redirect:" + projectUrlConfig.getSell() + "/seller/login?openid=" + openId;
    }


}
